package com.example.mydy;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Switch;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.example.mydy.model.UserInfo;
import com.example.mydy.utils.ActivityManager;
import com.example.mydy.utils.ImageUtils;
import com.example.mydy.utils.MockDataManager;
import com.example.mydy.utils.NetworkUtils;
import com.example.mydy.utils.SharedPreferencesManager;

import de.hdodenhof.circleimageview.CircleImageView;

public class UserSettingsActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "UserSettingsActivity";
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_NIGHT_MODE = "night_mode";
    private static final String KEY_AUTO_LOGIN = "auto_login";
    private static final String KEY_ALIPAY_ACCOUNT = "alipay_account";
    private static final String KEY_ALIPAY_NAME = "alipay_name";
    private static final String KEY_PHONE = "phone";

    private ImageButton btnBack;
    private CardView cardAccountInfo;
    private CardView cardAppPreferences;
    private CardView cardWithdrawalInfo;
    private CardView cardPrivacyPolicy;
    private Button btnLogout;
    
    private TextView tvUsername;
    private TextView tvUserLevel;
    private TextView tvUserVipLevel;
    private TextView tvUserNickname;
    private CircleImageView ivAvatar;
    
    private UserInfo currentUser;
    private ActivityManager activityManager;
    private SharedPreferences prefs;
    
    // 用于选择图片的ActivityResultLauncher
    private final ActivityResultLauncher<Intent> pickImageLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                    Uri imageUri = result.getData().getData();
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                        ivAvatar.setImageBitmap(bitmap);
                        // 保存图片
                        saveUserAvatar(bitmap);
                    } catch (Exception e) {
                        Toast.makeText(this, "加载图片失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_settings);
        
        // 初始化SharedPreferences
        prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        
        // 初始化ActivityManager
        activityManager = ActivityManager.getInstance(this);
        
        // 获取当前用户信息
        currentUser = MockDataManager.getInstance().getCurrentUser();
        if (currentUser == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 初始化视图
        initViews();
        
        // 设置点击监听器
        setupClickListeners();
        
        // 更新用户信息
        updateUserInfo();
    }
    
    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        cardAccountInfo = findViewById(R.id.card_account_info);
        cardAppPreferences = findViewById(R.id.card_app_preferences);
        cardWithdrawalInfo = findViewById(R.id.card_withdrawal_info);
        cardPrivacyPolicy = findViewById(R.id.card_privacy_policy);
        btnLogout = findViewById(R.id.btn_logout);
        
        tvUsername = findViewById(R.id.tv_username);
        tvUserNickname = findViewById(R.id.tv_user_nickname);
        tvUserLevel = findViewById(R.id.tv_user_level);
        tvUserVipLevel = findViewById(R.id.tv_user_vip_level);
        ivAvatar = findViewById(R.id.iv_avatar);
        
        // 初始化开关状态
        Switch switchNightMode = findViewById(R.id.switch_night_mode);
        Switch switchAutoLogin = findViewById(R.id.switch_auto_login);
        
        // 从SharedPreferences加载开关状态
        switchNightMode.setChecked(prefs.getBoolean(KEY_NIGHT_MODE, false));
        switchAutoLogin.setChecked(prefs.getBoolean(KEY_AUTO_LOGIN, true));
        
        // 设置开关监听
        switchNightMode.setOnCheckedChangeListener((buttonView, isChecked) -> {
            prefs.edit().putBoolean(KEY_NIGHT_MODE, isChecked).apply();
            Toast.makeText(this, "夜间模式将在下次启动时" + (isChecked ? "开启" : "关闭"), Toast.LENGTH_SHORT).show();
        });
        
        switchAutoLogin.setOnCheckedChangeListener((buttonView, isChecked) -> {
            prefs.edit().putBoolean(KEY_AUTO_LOGIN, isChecked).apply();
            Toast.makeText(this, "自动登录已" + (isChecked ? "开启" : "关闭"), Toast.LENGTH_SHORT).show();
        });
    }
    
    private void setupClickListeners() {
        btnBack.setOnClickListener(this);
        cardAccountInfo.setOnClickListener(this);
        cardAppPreferences.setOnClickListener(this);
        cardWithdrawalInfo.setOnClickListener(this);
        cardPrivacyPolicy.setOnClickListener(this);
        btnLogout.setOnClickListener(this);
        
        // 设置头像点击事件
        ivAvatar.setOnClickListener(v -> {
            showAvatarOptionsDialog();
        });
    }
    
    private void updateUserInfo() {
        if (currentUser != null) {
            tvUsername.setText(currentUser.getUsername());
            tvUserNickname.setText(currentUser.getNickname());
            tvUserLevel.setText(activityManager.getUserActivityLevelName(currentUser.getUsername()));
            
            String userLevel = currentUser.getLevel();
            if (userLevel != null && !userLevel.isEmpty()) {
                tvUserVipLevel.setText(userLevel);
                tvUserVipLevel.setVisibility(View.VISIBLE);
            } else {
                tvUserVipLevel.setVisibility(View.GONE);
            }
            
            // 加载用户头像
            String avatarUrl = currentUser.getAvatarUrl();
            if (avatarUrl != null && !avatarUrl.isEmpty()) {
                // 使用本地路径加载头像
                ImageUtils.loadAvatarIntoImageView(this, ivAvatar, avatarUrl);
            } else {
                // 检查是否有保存在本地的头像
                String localAvatarPath = ImageUtils.getUserAvatarPath(this, currentUser.getUsername());
                if (localAvatarPath != null) {
                    // 更新用户数据中的头像URL
                    MockDataManager.getInstance().updateUserAvatar(currentUser.getUsername(), localAvatarPath);
                    currentUser.setAvatarUrl(localAvatarPath);
                    ImageUtils.loadAvatarIntoImageView(this, ivAvatar, localAvatarPath);
                } else {
                    // 使用默认头像
                    ivAvatar.setImageResource(R.drawable.default_avatar);
                }
            }
        }
    }
    
    @Override
    public void onClick(View v) {
        int id = v.getId();
        
        if (id == R.id.btn_back) {
            finish();
        } else if (id == R.id.card_account_info) {
            // 跳转到账户信息界面
            showAccountInfoDialog();
        } else if (id == R.id.card_app_preferences) {
            // 显示应用设置对话框
            showAppPreferencesDialog();
        } else if (id == R.id.card_withdrawal_info) {
            // 显示提现信息设置对话框
            showWithdrawalInfoDialog();
        } else if (id == R.id.card_privacy_policy) {
            // 显示隐私政策
            showPrivacyPolicyDialog();
        } else if (id == R.id.btn_logout) {
            // 确认退出登录
            showLogoutConfirmationDialog();
        }
    }
    
    private void showAvatarOptionsDialog() {
        String[] options = {"从相册选择", "拍摄照片", "取消"};
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("更换头像")
                .setItems(options, (dialog, which) -> {
                    if (which == 0) {
                        // 从相册选择
                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        pickImageLauncher.launch(intent);
                    } else if (which == 1) {
                        // 拍摄照片
                        Toast.makeText(this, "拍摄照片功能开发中", Toast.LENGTH_SHORT).show();
                    }
                })
                .show();
    }
    
    private void saveUserAvatar(Bitmap bitmap) {
        // 在后台线程处理图片保存
        new Thread(() -> {
            // 保存图片到本地文件
            String avatarPath = ImageUtils.saveUserAvatar(this, bitmap, currentUser.getUsername());
            if (avatarPath != null) {
                // 更新用户数据中的头像路径
                boolean success = MockDataManager.getInstance().updateUserAvatar(currentUser.getUsername(), avatarPath);
                
                // 在UI线程更新界面和显示结果
                runOnUiThread(() -> {
                    if (success) {
                        Toast.makeText(this, "头像已更新", Toast.LENGTH_SHORT).show();
                        // 更新当前用户对象的头像URL
                        currentUser.setAvatarUrl(avatarPath);
                    } else {
                        Toast.makeText(this, "头像更新失败", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                runOnUiThread(() -> {
                    Toast.makeText(this, "保存头像失败", Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }
    
    private void showAccountInfoDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_account_info, null);
        
        // 初始化对话框视图
        EditText etNickname = dialogView.findViewById(R.id.et_nickname);
        EditText etPhone = dialogView.findViewById(R.id.et_phone);
        TextView tvInviteCode = dialogView.findViewById(R.id.tv_invite_code);
        
        // 设置当前值
        etNickname.setText(currentUser.getNickname());
        String phone = prefs.getString(KEY_PHONE, "");
        etPhone.setText(phone);
        
        // 设置邀请码
        String inviteCode = MockDataManager.getInstance().getInviteCode(currentUser.getUsername());
        tvInviteCode.setText(inviteCode != null ? inviteCode : "暂无邀请码");
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("账户信息")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    // 保存修改
                    String newNickname = etNickname.getText().toString().trim();
                    String newPhone = etPhone.getText().toString().trim();
                    
                    if (!newNickname.isEmpty() && !newNickname.equals(currentUser.getNickname())) {
                        currentUser.setNickname(newNickname);
                        MockDataManager.getInstance().updateUser(currentUser);
                        tvUserNickname.setText(newNickname);
                    }
                    
                    if (!newPhone.isEmpty() && !newPhone.equals(phone)) {
                        prefs.edit().putString(KEY_PHONE, newPhone).apply();
                    }
                    
                    Toast.makeText(this, "账户信息已更新", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void showAppPreferencesDialog() {
        // 这里简化处理，由于应用偏好已在主界面显示，可以提示用户直接在主界面修改
        Toast.makeText(this, "请在设置页面直接调整应用偏好", Toast.LENGTH_SHORT).show();
    }
    
    private void showWithdrawalInfoDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_withdrawal_info, null);
        
        // 初始化对话框视图
        EditText etAlipayAccount = dialogView.findViewById(R.id.et_alipay_account);
        EditText etAlipayName = dialogView.findViewById(R.id.et_alipay_name);
        
        // 设置当前值
        String alipayAccount = prefs.getString(KEY_ALIPAY_ACCOUNT, "");
        String alipayName = prefs.getString(KEY_ALIPAY_NAME, "");
        
        etAlipayAccount.setText(alipayAccount);
        etAlipayName.setText(alipayName);
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提现信息设置")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    // 保存修改
                    String newAlipayAccount = etAlipayAccount.getText().toString().trim();
                    String newAlipayName = etAlipayName.getText().toString().trim();
                    
                    if (newAlipayAccount.isEmpty() || newAlipayName.isEmpty()) {
                        Toast.makeText(this, "请填写完整的支付宝信息", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    // 保存到SharedPreferences
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putString(KEY_ALIPAY_ACCOUNT, newAlipayAccount);
                    editor.putString(KEY_ALIPAY_NAME, newAlipayName);
                    editor.apply();
                    
                    Toast.makeText(this, "提现信息已保存", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void showPrivacyPolicyDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("隐私政策")
               .setMessage("这是我们的隐私政策内容...\n\n" +
                          "我们重视您的隐私，并致力于保护您的个人信息。本隐私政策描述了我们如何收集、使用、存储和保护您的信息。" +
                          "使用我们的服务即表示您同意本隐私政策中描述的做法。")
               .setPositiveButton("我同意", null)
               .show();
    }
    
    private void showLogoutConfirmationDialog() {
        new AlertDialog.Builder(this)
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 执行退出登录操作
                    logout();
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void logout() {
        // 清除登录状态
        SharedPreferencesManager.setLoggedIn(this, false);
        SharedPreferencesManager.setUsername(this, null);
        
        // 清除令牌
        NetworkUtils.clearAuthToken(this);
        NetworkUtils.clearUsername(this);
        
        // 清除当前用户
        MockDataManager.getInstance().logout();
        
        // 显示提示
        Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();
        
        // 返回登录页面
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }
} 